<template>
  <el-form
    ref="searchForm"
    :inline="true"
    :model="queryParams"
    :label-width="labelWidth"
    label-position="top"
    class="search-form"
  >
    <el-row :gutter="10">
      <el-col
        :xs="24"
        :sm="12"
        :md="8"
        :lg="6"
        :xl="4"
        v-for="(item, index) in frame"
        :key="index"
        :style="{ minWidth: item.minWidth }"
      >
        <el-form-item
          v-if="item.type === 1"
          :key="'input' + index"
          :label-width="item.labelWidth ? item.labelWidth : labelWidth"
          :prop="item.key"
        >
          <el-input
            v-model="queryParams[item.key]"
            :placeholder="
              item.placeholder ? item.placeholder : '请输入' + item.label
            "
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        
        <el-form-item
          v-else-if="item.type === 2"
          :key="'select' + index"
          :label-width="item.labelWidth ? item.labelWidth : labelWidth"
          :prop="item.key"
        >
          <el-select
            v-model="queryParams[item.key]"
            :filterable="item.filterable"
            :multiple="item.multiple"
            clearable
            :placeholder="
              item.placeholder ? item.placeholder : '请选择' + item.label
            "
            :style="`minWidth: ${item.width}px`"
          >
            <el-option
              v-for="(items, indexs) in item.options"
              :key="indexs"
              :label="items.label"
              :value="items.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item
          v-else-if="item.type === 3"
          :key="'date1' + index"
          :label-width="item.labelWidth ? item.labelWidth : labelWidth"
          :prop="item.key"
        >
          <el-date-picker
            v-model="queryParams[item.key]"
            :type="item.dateType ? item.dateType : 'datetimerange'"
            range-separator="-"
            :start-placeholder="item.label + '开始日期'"
            :end-placeholder="item.label + '结束日期'"
            :value-format="item.format ? item.format : 'yyyy-MM-dd HH:mm:ss'"
            :unlink-panels="true"
            :default-time="
              item.defaultTime ? '23:59:59' : ['00:00:00', '23:59:59']
            "
          />
        </el-form-item>

        <el-form-item
          v-else
          :key="'date2' + index"
          :prop="item.key"
          :label-width="item.labelWidth ? item.labelWidth : labelWidth"
        >
          <el-date-picker
            v-model="queryParams[item.key]"
            type="date"
            :value-format="item.format ? item.format : 'yyyy-MM-dd HH:mm:ss'"
            :placeholder="`选择${item.label}日期`"
            style="width: 100%"
          />
        </el-form-item>
      </el-col>
      <el-col
        :xs="24"
        :sm="12"
        :md="8"
        :lg="6"
        :xl="4"
        :style="{ minWidth: btnWidth }"
      >
        <el-form-item ref="btns">
          <el-button type="primary" icon="el-icon-search" @click="handleQuery"
            >搜索</el-button
          >
          <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
          <el-button
            v-if="isDownload"
            icon="el-icon-download"
            @click="handleExport"
            >导出</el-button
          >
          <el-button v-if="showAdd" type="primary" plain icon="el-icon-plus" @click="handleAdd">新增</el-button>
          <slot />
          <el-button
            ref="toggleBtn"
            type="primary"
            @click="toggleSearch"
            v-if="isShowToggleBtn"
          >
            {{ word }}
            <i
              :class="showAll ? 'el-icon-arrow-up ' : 'el-icon-arrow-down'"
            ></i>
          </el-button>
        </el-form-item>
      </el-col>
    </el-row>
  </el-form>
</template>
<script>
export default {
  name: "SearchForm",
  props: {
    searchFrame: {
      type: Array,
      default: () => [],
    },
    queryParams: {
      type: Object,
      default: () => {},
    },
    labelWidth: {
      type: String,
      default: "90px",
    },
    isDownload: {
      type: Boolean,
      default: false,
    },
    showAdd: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      date: [],
      api: {},
      showAll: false,
      frame: [],
      windowWidth: window.innerWidth,
      isShowToggleBtn: false,
      btnWidth: 0,
      isFlag: 0,
      spliceLen: 0,
    };
  },
  mounted() {
    this.updateWindowWidth();
    window.addEventListener("resize", this.updateWindowWidth);
  },
  beforeDestroy() {
    window.removeEventListener("resize", this.updateWindowWidth);
  },
  watch: {
    searchFrame: {
      handler(val, oldval) {
        if(val !== oldval){
          this.frame = this.createFrame()
        }
      },
      deep: true,
    },
  },
  computed: {
    word() {
      if (this.showAll == false) {
        return "展开搜索";
      } else {
        return "收起搜索";
      }
    },
  },
  methods: {
    computedCol(){
      this.windowWidth = window.innerWidth;
      let defaultLen = 0;
      let col = 0;  
      if (this.windowWidth >= 1920) {
        defaultLen = 18;
        col = 6;
      } else if (this.windowWidth >= 1200) {
        defaultLen = 12;
        col = 4;
      } else if (this.windowWidth >= 992) {
        defaultLen = 9;
        col = 3;
      } else if (this.windowWidth >= 768) {
        defaultLen = 6;
        col = 2;
      } else {
        defaultLen = 0;
        col = 0;
      }
      return {
        defaultLen,
        col
      }
    },
    createFrame(){
      return JSON.parse(JSON.stringify(this.searchFrame));
    },
    // 根据窗口宽度调整布局
    updateWindowWidth() {
      let frame = this.createFrame();
      let frameLen = frame.length;

      // 计算原始按钮的宽度
      let initBtnWidth = this.$refs.btns.$children.reduce((pre, cur) => {
        return pre + 10 + cur.$el.offsetWidth || 0;
      }, 0);
      initBtnWidth += 20;
      let toggleBtnWidth = 138;
      // isFlag来判断是否是第一次加载页面，第一次加载页面，toggleBtn不在this.$refs.btns.$children中
      if (this.isFlag + 1 >= this.$refs.btns.$children.length) {
        toggleBtnWidth = 0;
      }
      this.isFlag = this.$refs.btns.$children.length;

      // 计算原始按钮所占长度
      let btnLen = 0;
      let { defaultLen, col } = this.computedCol();
      this.searchBoxWidth = this.$refs.searchForm.$el.offsetWidth + 10;

      this.frame = frame;
      if (defaultLen <= frameLen) {
        this.isShowToggleBtn = true;
        this.btnWidth = initBtnWidth + toggleBtnWidth;
        btnLen = Math.ceil((this.btnWidth / this.searchBoxWidth) * col);
        this.spliceLen = defaultLen - btnLen;
        this.frame = frame.splice(0, this.spliceLen);
      } else {
        // 如果按钮加框架小于等于默认长度，则不显示按钮
        btnLen = Math.ceil((initBtnWidth / this.searchBoxWidth) * col);
        if (btnLen + frameLen <= defaultLen) {
          this.isShowToggleBtn = false;
          this.btnWidth = initBtnWidth;
        } else {
          this.isShowToggleBtn = true;
          this.btnWidth = initBtnWidth + toggleBtnWidth;
          btnLen = Math.ceil((this.btnWidth / this.searchBoxWidth) * col);
          this.spliceLen = frameLen - btnLen + 1;
          this.frame =  frame.splice(0, this.spliceLen);
        }
      }
      this.btnWidth += "px";
    },

    toggleSearch() {
      let frame = this.createFrame();
      this.showAll = !this.showAll;
      if (this.showAll) {
        this.frame = frame;
      } else {
        this.frame = frame.splice(0, this.spliceLen);
        this.showAll = false;
      }
    },

    /** 新增 */
    handleAdd(){
      this.$emit("add")
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      for (let i in this.queryParams) {
        if (!this.queryParams[i] && this.queryParams[i] != 0) {
          delete this.queryParams[i];
        }
      }
      this.$emit("update:queryParams", this.queryParams);
      this.$emit("search");
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.frame.map((item) => {
        this.$set(this.queryParams, item.key, "");
      });
      this.handleQuery();
    },

    /** 导出按钮操作 */
    handleExport() {
      this.$emit("download");
    },
  },
};
// 使用说明
// 名称：SearchForm组件
// 作用：一般用于list列表页的搜索，并且附上搜索、清空、导出，按钮设置slot，可以另外加
// 父组件例:
//<SearchForm ref="searchForm" :queryParams.sync="queryParams" :formData="formData"  @search="handleSearch" />

// --------------------------------------------------------------
// 父组件的参数说明：
// formData：循环的结构数据（必传)
// queryParams：搜索的参数(必传)
// labelWidth: 标题的长度
// btnWidth：全部的按钮宽度
// deriveInfo:导出数据，title（导出的列表名，选填）和fun（接口名称，必填）
// ---------------------------------------------------------------
// formData:为搜索数据选项
// formData: [
// { type: 3, label: '日期', key: 'dateRange',dateType:'daterange',format:'yyyy-MM-dd',minWidth:'400px'},
// { type: 1, label: '分数', key: 'score'},
// { type: 2, label: '贷款类型',key: 'refinancing', optionsName:'loadType'}
// ],
// ------------------------------------------------------
// item字段：
// type为类型，1为input，2为select，3为范围日期， 4为单日期
// label为搜索框名称
// placeholder为搜索框提示语
// key为对象相关联的属性名
// width为输入框的宽度
// minWidth为col的最小宽度
// labelWidth为当前搜索框标题的长度
// -type == 2
// optionsName为字典状态名，数据从store中取
// filterable是否可搜索，默认false
// multiple 是否多选，默认false
// -type == 3
// dateType  默认datetimerange
// format  默认yyyy-MM-dd HH:mm:ss
// ----------------------------------------------------------------------------------------------------------------------
</script>

<style lang="scss" scoped>
.el-form--inline .el-form-item,
.el-select,
.el-range-editor.el-input__inner {
  width: 100%;
}

.el-form-item {
  margin-bottom: 10px;
}
</style>
